using System.Text.RegularExpressions;

namespace Prometheus.Binding.Validation.Rules.Simple
{
    /// <summary>
    /// Call Regex.IsMatch
    /// </summary>
    public class proRegexMatchRule : proValidationRuleBase
    {
        private const string BaseErrorText = "Bad format";

        public proRegexMatchRule()
        {
            ErrorText = BaseErrorText;
        }

        /// <summary>
        /// Text about regex pattern
        /// </summary>
        public string AboutFormatText
        {
            set { ErrorText = BaseErrorText + ":" + value; }
        }

        /// <summary>
        /// Regex pattern
        /// </summary>
        public string Pattern { get; set; }

        public override void Validate(object value, object dataContext)
        {
            if (value == null) return; //Assume, that null always match the pattern

            var regex = new Regex(Pattern, RegexOptions.IgnoreCase);
            bool isMatch = regex.IsMatch(value.ToString());
            if (!isMatch)
            {
                ThrowInvalid();
            }
        }
    }
}